#!/usr/bin/env bash
# Copyright 2023 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__(){
  cat <<EOF
configVersion: v1
kubernetesValidating:
- name: customprometheusrules-policy.deckhouse.io
  group: main
  rules:
  - apiGroups:   ["deckhouse.io"]
    apiVersions: ["v1"]
    operations:  ["CREATE", "UPDATE"]
    resources:   ["customprometheusrules"]
    scope:       "Cluster"
EOF
}

function __main__() {
  rules_yaml=$(mktemp -t rules.XXXXXX)
  trap 'rm -f -- "$rules_yaml"' EXIT

  context::jq -r '.review.request.object.spec' | yq eval -P - > "$rules_yaml"
  # Capture stderr to variable, ignoring stdout.
  if ! check_result=$(promtool check rules "$rules_yaml" 2>&1); then
    # Remove first line "  FAILED:" from the output.
    # Remove filename from each line of the output.
    message=$(echo "$check_result" | tail -n +2 | cut -d " " -f2-)
    jq -nc --arg message "$message" '
      {
        "allowed": false,
        "message": $message
      }
      ' > $VALIDATING_RESPONSE_PATH
    exit 0
  fi

  # Allowed response.
  jq -nc '{"allowed": true}' > $VALIDATING_RESPONSE_PATH
}

hook::run $@
